package com.tuomaxu.utils;

import com.tuomaxu.pojo.Mapper;
import com.tuomaxu.servlet.HttpServlet;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ServerXmlParserUtil {

    public static int port = 8080;
    public static String appBase = null;


    public static Mapper parser(String name){
        Map<String, Map<String, HttpServlet>> map = new HashMap<>();
        InputStream resourceAsStream = ServerXmlParserUtil.class.getClassLoader().getResourceAsStream(name);
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            //查询Connector标签，获取port属性
            List<Node> connectors = rootElement.selectNodes("//Connector");
            for (Node connector : connectors) {
                Element element = (Element) connector;
                String portStr = element.attributeValue("port");
                port = Integer.parseInt(portStr);
                break;
            }

            //查询Host标签，获取appBase路径
            List<Node> hosts = rootElement.selectNodes("//Host");
            for (Node host : hosts) {
                Element element = (Element) host;
                appBase = element.attributeValue("appBase");
            }

            //查询Context标签，获取context相对路径
            //通过webapp+相对路径，加载web.xml
            // 解析web.xml ,获取servlet信息 构建Mapper
            List<Node> contexts = rootElement.selectNodes("//Context");
            for (Node context : contexts) {
                Element element = (Element) context;
                //获取请求路径path和docBase，
                //这里docBase是相对路径，根路径为appBase
                String path = element.attributeValue("path");
                String docBase = element.attributeValue("docBase");

                //通过appBase和docBase拼接web.xml所在在路径
                String webxmlPath = appBase + docBase + "/web.xml";
                File file = new File(webxmlPath);
                if(!file.exists()){
                    System.out.println("web.xml不存在");
                    continue;
                }
                //解析web.xml生成servletMap
                Map<String, HttpServlet> servletMap = WebXmlParseUtil.parse(file);

                //以path为key，servletMap为value创建map
                map.put(path,servletMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new Mapper(map);
    }

}
